package com.zzx.utils;


import java.io.Reader;


import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class myBatisUtil {
	private static final String resource = "applicationContext.xml";
	private static SqlSessionFactory sqlSessionFactory = null;
	private static ThreadLocal<SqlSession> threadLocal =new ThreadLocal<SqlSession>();
	static {
		Reader reader = null;
		try {
			reader = Resources.getResourceAsReader(resource);
			sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static SqlSessionFactory getSqlSessionFactory() {
		return sqlSessionFactory;
	}
	public static SqlSession getSession() {
		SqlSession session = threadLocal.get();
//		sessionΪnullһµsession
		if(session==null) {
			session =(sqlSessionFactory!=null)? sqlSessionFactory.openSession(true): null;
			threadLocal.set(session);
		}
		return session;
	}
	public static void closeSession() {
		SqlSession session = threadLocal.get();
		threadLocal.set(null);
		session.close();
	}
}

